import { _decorator, Component, Node, Vec2, Vec3 } from 'cc';
import { GameData } from '../../system/GameData';
const { ccclass, property } = _decorator;

@ccclass('MoveByLt')
export class MoveByLt extends Component {
    private mLtPoint: [number[]] = [[]];
    private mV2StartPoint: Vec2 = null;
    private mV2EndPoint: Vec2 = null
    private mSpeed: number = null;
    private mStart: boolean = false;
    private mCurDistance = 0;
    private mIsFinish = false;
    private mIndex = 0;
    start() {

    }

    InitPointLt(lt: [number[]], speed: number) {
        this.mSpeed = speed;
        this.mLtPoint = lt;
        this.mIndex = 0;
        this.UpdateSEPoint();
        this.mStart = true;
    }

    UpdateSEPoint() {
        if (this.mIndex == this.mLtPoint.length - 1) return;
        this.mV2StartPoint = new Vec2(this.mLtPoint[this.mIndex][0], this.mLtPoint[this.mIndex][1]);
        this.mV2EndPoint = new Vec2(this.mLtPoint[this.mIndex + 1][0], this.mLtPoint[this.mIndex + 1][1]);
    }

    update(deltaTime: number) {
        if (GameData.isPause) return;
        if (!this.mStart || this.mIsFinish == true) return;
        let totalDistance = this.mV2StartPoint.clone().subtract(this.mV2EndPoint).length();
        let curDistance = deltaTime * this.mSpeed;
        this.mCurDistance += curDistance;
        let direction = this.mV2EndPoint.clone().subtract(this.mV2StartPoint).normalize();
        let currentPosition = this.mV2StartPoint.clone().add(direction.multiplyScalar(this.mCurDistance));
        this.node.setPosition(new Vec3(currentPosition.x, currentPosition.y, 0));
        if (this.mCurDistance >= totalDistance && this.mIndex >= this.mLtPoint.length - 1) {
            this.mIsFinish = true;
            this.mSpeed = 0;
            this.node.emit("MoveFinish");
        } else if (this.mCurDistance >= totalDistance && this.mIndex < this.mLtPoint.length - 1) {
            this.mCurDistance = 0;
            this.mIndex++;
            this.UpdateSEPoint();
        }
    }

    get Speed() {
        return this.mSpeed;
    }

    set Speed(value) {
        this.mSpeed = value;
    }
}


